package my.app;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListAdapter;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivty extends Activity  {
 TabHost mTabHost;
 FrameLayout mFrameLayout;
 
 TextView username;
 TextView password;
 TextView latlonText;
 TextView addressText;
 TextView host;
 Button loginButton;
 
 Context context;

 /** Called when the activity is first created.*/
 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_view);
    context = this;
    
    username = (TextView) findViewById(R.id.myuser);
    password = (TextView) findViewById(R.id.mypass);
    latlonText = (TextView) findViewById(R.id.mylatlon);
    addressText = (TextView) findViewById(R.id.myaddress);
    host = (TextView) findViewById(R.id.myhost);
    loginButton = (Button) findViewById(R.id.mybutton);
    
    //Set sharedpreferences
	SharedPreferences sp = getSharedPreferences("DClisP", Activity.MODE_PRIVATE);
	if (sp.getString("username", "") != null) {
		username.setText(sp.getString("username", ""));
	}
	if (sp.getString("password", "") != null) {
		password.setText(sp.getString("password", ""));
	}
	if (sp.getString("host", "") != null) {
		host.setText(Settings.getInstance().getHost());
	}
    
    
    
    
    LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

	mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
			new LocationListener() {
				
		@Override
		public void onLocationChanged(Location loc)

		{
			//Set latlon..
			final double lat = loc.getLatitude();
			final double lon = loc.getLongitude();
			String s = "Lat: "+lat+" Lon: "+lon;
			latlonText.setText("Your Address:");
			
			
			
			
			//Set Address
			Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());
			List<Address> as = null;
			try {
				as = gc.getFromLocation(lat, lon, 1);
			} catch (Exception e) {
			}
			String ss = "";
			if (as == null) {
				ss = "Address Not Found..";
			}
			else if (as.size() > 0) {
				Address add = as.get(0);
				ss  = add.getAddressLine(0);
			}
			else {
				ss = "Address Not Found.."; 
			}
			addressText.setText(ss);
			
			
			//Set button login and creat mainactivty
			loginButton.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Settings s = Settings.getInstance();
					s.setUsername(username.getText().toString());
					s.setPassword(password.getText().toString());
					s.setHost(host.getText().toString());
					s.setLat(lat);
					s.setLon(lon);
					
					SharedPreferences sp = getSharedPreferences("DClisP", Activity.MODE_PRIVATE);
					SharedPreferences.Editor editor = sp.edit();
					editor.putString("username", username.getText().toString());
					editor.putString("password", password.getText().toString());
					editor.putString("host", host.getText().toString());
					editor.commit();
					
					
					//LOgin..
					boolean flag = false;
					
					try {
						SoapObject request = new SoapObject("service4Cab", "login");
						request.addProperty("username", username.getText().toString());
						request.addProperty("password", password.getText().toString());
						SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
						envelope.setOutputSoapObject(request);
						AndroidHttpTransport aht = new AndroidHttpTransport(Settings.getInstance().getHost());
						
						aht.call("service4Cab", envelope);
						
						SoapObject result = (SoapObject) envelope.bodyIn;
						flag = Boolean.parseBoolean(result.getProperty("return").toString());
					} catch (Exception e) {
					}
					
					if (flag == true) {
						AlertDialog.Builder builder = new AlertDialog.Builder(context);
						builder.setMessage("Login Succesful")
						       .setCancelable(false)
						       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
						           public void onClick(DialogInterface dialog, int id) {
						        	   Intent i = new Intent(context, Bitirme.class);
						        	   startActivity(i);
						        	   finish();
						           }
						       });
						AlertDialog alert = builder.create();
						alert.show();
					}
					else{
						AlertDialog.Builder builder = new AlertDialog.Builder(context);
						builder.setMessage("Login Failed")
						       .setCancelable(false)
						       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
						           public void onClick(DialogInterface dialog, int id) {
						           }
						       });
						AlertDialog alert = builder.create();
						alert.show();
					}
				}
			});
			
			
			
		}

		@Override
		public void onProviderDisabled(String provider)

		{

			Toast.makeText(getApplicationContext(),

			"Gps Disabled",

			Toast.LENGTH_SHORT).show();

		}

		@Override
		public void onProviderEnabled(String provider)

		{

			Toast.makeText(getApplicationContext(),

			"Gps Enabled",

			Toast.LENGTH_SHORT).show();

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras)

		{

		}

	});
    
 }
}
